package ltd.newbee.mall.config;

import com.paypal.core.PayPalHttpClient;
import com.paypal.http.HttpResponse;
import com.paypal.orders.PurchaseUnitRequest;
import ltd.newbee.mall.util.paypal.CaptureOrder;
import ltd.newbee.mall.util.paypal.CreateOrder;
import ltd.newbee.mall.util.paypal.OrderExecutor;
import ltd.newbee.mall.util.paypal.RefundOrder;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.List;

@RefreshScope
@Component
public class PayPalComponent {

    @Value("${paypal.cancel.url}")
    private String paypalCancelUrl;

    @Value("${paypal.return.url}")
    private String paypalReturnUrl;

    @Autowired
    private PayPalHttpClient client;

    /**
     * 创建订单
     * @param orderId 贝宝返回的id
     * @param purchaseUnitRequest 订单项
     * @return 响应结果
     * @throws IOException
     */
    public HttpResponse<?> createOrder(String orderId, List<PurchaseUnitRequest> purchaseUnitRequest) throws IOException {
        if (purchaseUnitRequest == null || purchaseUnitRequest.isEmpty()) {
            throw new RuntimeException("订单项为空");
        }
        CreateOrder createOrder = new CreateOrder();
        createOrder.setPaypalCancelUrl(paypalCancelUrl);
        createOrder.setPaypalReturnUrl(paypalReturnUrl);
        createOrder.setPurchaseUnitRequest(purchaseUnitRequest);
        OrderExecutor orderExecutor = new OrderExecutor(createOrder);
        return orderExecutor.getResponseMessage(orderId, client);
    }

    /**
     * 执行扣款
     * @param orderId 贝宝返回的id
     * @return 响应结果
     * @throws IOException
     */
    public HttpResponse<?> captureOrder(String orderId) throws IOException {
        return new OrderExecutor(new CaptureOrder()).getResponseMessage(orderId,client);
    }

    /**
     *
     * @param catureId 扣款的id
     * @param money 退回的金额
     * @return
     * @throws IOException
     */
    public HttpResponse<?> refundOrder(String catureId,String money) throws IOException {
        if (StringUtils.isEmpty(money)) {
            throw new RuntimeException("金额不能为空");
        }
        if (!NumberUtils.isNumber(money)) {
            throw new RuntimeException("正确的金额");
        }
        RefundOrder refundOrder = new RefundOrder();
        refundOrder.setRefundmoney(money);
        return new OrderExecutor(refundOrder).getResponseMessage(catureId,client);
    }
}
